//
//  MXLockSudoko.m
//  MXLoginMethodsDomo
//
//  Created by 马彦 on 16/9/27.
//  Copyright © 2016年 MX. All rights reserved.
//
/**
 *
 *
 *          九宫格解锁视图
 *
 *
 *
 */

#import "MXLockSudoko.h"
#import "MXLockConfig.h"
#import "MXLockCircle.h"

@interface MXLockSudoko ()

/**圆数组*/
@property (nonatomic, strong) NSMutableArray *circleArrayM;
/**选中圆数组*/
@property (nonatomic, strong) NSMutableArray *selectedCircleArrayM;

/**要切的边缘*/
@property (nonatomic, assign) CGFloat circleMargin;

@property (nonatomic, assign) CGPoint currentPoint;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign, getter = isErrorPassword) BOOL errorPassword;
@property (nonatomic, assign, getter = isDrawing) BOOL drawing;

@end

@implementation MXLockSudoko

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setup];
        [self initCircles];
    }
    return self;
}

- (void)setup {
    self.backgroundColor = [UIColor clearColor];
    self.clipsToBounds = YES;
    
    self.circleArrayM = [NSMutableArray array];
    self.selectedCircleArrayM = [NSMutableArray array];
    self.circleMargin = MXLOCK_SUDOKO_SIDE_LENGTH / 15 ;
}

/**画圆*/
- (void)initCircles {
    
    for (int i = 0; i < 9; i++) {
        /**
         把宽度分为15份为_circleMargin，每个圆占3份: 3 * 3 * _circleMargin  剩下6份为4个间距：_circleMargin * 6 *0.25
            x = _circleMargin * (i % 3) * 3 + _circleMargin * (i % 3) * 6 * 0.25 + _circleMargin * 6 * 0.25 = _circleMargin * (4.5 * (i % 3) + 1.5)
         */
        float x = _circleMargin * (4.5 * (i % 3) + 1.5);
        float y = _circleMargin * (4.5 * (i / 3) + 1.5);
        
        MXLockCircle * circleView = [[MXLockCircle alloc] initWithDiameter:_circleMargin * 3];
        circleView.frame = CGRectMake(x, y, _circleMargin * 3, _circleMargin * 3);
        circleView.tag = MXLOCK_SUDOKO_LEVEL_BASE + i;
        [_circleArrayM addObject:circleView];
        [self addSubview:circleView];
    }
}

- (void)showErrorPassword:(NSString *)errorPassword {
    self.errorPassword = YES;
    NSMutableArray *numbers = [NSMutableArray arrayWithCapacity:errorPassword.length];
    
    for (int i = 0; i < errorPassword.length; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSString *numberStr = [errorPassword substringWithRange:range];
        
        NSNumber *number = [NSNumber numberWithInt:numberStr.intValue];
        [numbers addObject:number];
        [self.circleArrayM[number.intValue] updateCircleState:MXLockCircleStateError];
        [self.selectedCircleArrayM addObject:self.circleArrayM[number.intValue]];
    }
    
    [self setNeedsDisplay];
    
    if (!_timer) {
        [_timer invalidate];
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(reset) userInfo:nil repeats:NO];
}

- (void)reset {
    if (!self.drawing) {
        self.errorPassword = NO;
        for (MXLockCircle *circle in self.circleArrayM) {
            [circle updateCircleState:MXLockCircleStateNormal];
        }
        [self.selectedCircleArrayM removeAllObjects];
        [self setNeedsDisplay];
    }
}

#pragma mark - 触屏
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    self.drawing = NO;
    if (self.errorPassword) {
        [self reset];
    }
    [self updateTrack:[[touches anyObject] locationInView:self]];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.drawing = YES;
    [self updateTrack:[[touches anyObject] locationInView:self]];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self endTrack];
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self endTrack];
}

- (void)updateTrack:(CGPoint)point {
    self.currentPoint = point;
    
    for (MXLockCircle *circle in self.circleArrayM) {
        CGFloat xABS = fabs(point.x - circle.center.x);
        CGFloat yABS = fabs(point.y - circle.center.y);
        
        CGFloat radius = self.circleMargin * 3 / 2;
        
        
        if (xABS <= radius && yABS <= radius) {
           
            if (circle.state == MXLockCircleStateNormal) {
                
                [circle updateCircleState:MXLockCircleStateSelected];
                [self.selectedCircleArrayM addObject:circle];
                
            }
            break;
        }
    }
    [self setNeedsDisplay];
}

- (void)endTrack {
    _drawing = NO;
    
    NSString *password = @"";
    for (int i = 0; i < self.selectedCircleArrayM.count; i++) {
        MXLockCircle *circle = self.selectedCircleArrayM[i];
        password = [password stringByAppendingFormat:@"%ld",circle.tag - MXLOCK_SUDOKO_LEVEL_BASE];
    }
    [self reset];
    
    if ([_delegate respondsToSelector:@selector(sudoko:passwordDidCireate:)]) {
        [_delegate sudoko:self passwordDidCireate:password];
    }
}

#pragma mark - draw 

- (void)drawRect:(CGRect)rect {
    if (self.selectedCircleArrayM.count == 0) {
        return ;
    }
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, MXLOCK_SUDOKO_TRACK_WIDTH);
    self.errorPassword ? [MXLOCK_COLOR_ERROR set] : [MXLOCK_COLOR_NORMAL set];
    
    CGPoint addlines[9];
    int count = 0;
    
    for (MXLockCircle *circle in _selectedCircleArrayM) {
        CGPoint point = CGPointMake(circle.center.x, circle.center.y);
        addlines[count ++] = point;
    }
    
    CGContextAddLines(context, addlines, count);
    CGContextStrokePath(context);
    
    if (!self.errorPassword) {
        UIButton *lastBtn = self.selectedCircleArrayM.lastObject;
        CGContextMoveToPoint(context, lastBtn.center.x, lastBtn.center.y);
        CGContextAddLineToPoint(context, self.currentPoint.x, self.currentPoint.y);
        CGContextStrokePath(context);
    }
}



@end
